/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-10
 */
package com.chenuu.integration.httpclient.dropbox;

import java.util.List;

import com.dropbox.client2.jsonextract.JsonExtractionException;
import com.dropbox.client2.jsonextract.JsonExtractor;
import com.dropbox.client2.jsonextract.JsonMap;
import com.dropbox.client2.jsonextract.JsonThing;

/**
 * A page of {@link DeltaEntry DeltaEntry}s (returned by {@link #delta delta}).
 */
public class DeltaPage<MD> {
    /**
     * If <code>true</code>, then you should reset your local state to be an empty
     * folder before processing the list of delta entries.  This is only <code>true</code>
     * in rare situations.
     */
    public final boolean reset;

    /**
     * A string that is used to keep track of your current state.  On the next call to
     * {@link #delta delta}, pass in this value to pick up where you left off.
     */
    public final String cursor;

    /**
     * Apply these entries to your local state to catch up with the Dropbox server's state.
     */
    public final List<DeltaEntry<MD>> entries;

    /**
     * If <code>true</code>, then there are more entries available; you can call {@link
     * #delta delta} again immediately to retrieve those entries.  If <code>false</code>,
     * then wait at least 5 minutes (preferably longer) before checking again.
     */
    public final boolean hasMore;

    public DeltaPage(boolean reset, List<DeltaEntry<MD>> entries, String cursor, boolean hasMore) {
        this.reset = reset;
        this.entries = entries;
        this.cursor = cursor;
        this.hasMore = hasMore;
    }

    public static <MD> DeltaPage<MD> extractFromJson(JsonThing j, JsonExtractor<MD> entryExtractor) throws JsonExtractionException {
        JsonMap m = j.expectMap();
        boolean reset = m.get("reset").expectBoolean();
        String cursor = m.get("cursor").expectString();
        boolean hasMore = m.get("has_more").expectBoolean();
        List<DeltaEntry<MD>> entries = m.get("entries").expectList().extract(new DeltaEntry.JsonExtractor<MD>(entryExtractor));

        return new DeltaPage<MD>(reset, entries, cursor, hasMore);
    }

}